package com.ews.auth.service;

import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ews.auth.util.HttpClientUtils;
import com.ews.auth.util.RasUtil;
import com.ews.auth.util.SignUtil;

public class StyrzService {

    private static String signType = "1"; //1: 本地签名 2：网络签名
    private static String appid = "WVEVWOBRVN";
    private static String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL9X66Fy/65jsefzPzlxTS2wb/4mSmMy3v+180lT/2bsprhccRCyQRZ3Z1tcl3oYV1aUkmydbhAxDVogoBM/fwbvk4gjIbJMZRJRlUQfV6gE+V8lMhtSq9XoKZYw8nyAiiNKgyGs/jhP038KYLfdwNil4afqXJsZ3tFYpGhez7uXAgMBAAECgYEAoKEFXWa1/8cPrcHFfMqB2O46RigM4JPvIsmzMAbE7LmUCEcKX9LU0zBv4wGq5EOU5kkZVvceU5dqNxQWbbIrRscrybyr7xtbHTP79+4LmRqvy5WIfOs5TiZ1EBVMWdZ4D99//JpxKLzFp+6t7CHZ5NdJOoma6Vm5GieAcvVZTGECQQD+CtfGIoRAyzWaFEkWdTdHuFvfZF5CK9mFsTmfEpFb9cqkBobCfrew0Ra93jAwT/mpWbFHG9kWwHJRd4huleCRAkEAwNFjteL6eTyL0UM7+TEZuF5glaVgGMIXQLctEIe9073TwBWJ0FgTaIr/AIxv9P8LI5ICo4tErYNoysZwaeTtpwJAA5vd0te8rzrzyPuOyj3iCifJTlQbrq72yRpqaiMWY4sLVOcu1OZ974oY25ujbZxFPK2kghEYNWWIejXLf16rsQJASwGpPhobwYmyAiebbuaQ0M212MDKTxdBoGUhXKrRR0sy0igOwkNg2Wwoonf/HVkRZjboW+JTRwQ1gZwMIsVxRQJBAO7mwI73pIqnzw2T4/KHqxT1xPvsdqmSUam7q4uekqqkazNW8IftpHzAepjvJjCF+slAcgw0xCoUPd6lQq985qE=";

    private static String origin = "0";
    private static String version = "1.0";
    private static String charset = "UTF-8";

    public static Map<String, String> initMap(String interface_id) {
        Map<String, String> map =new HashMap();
        map.put("app_id", appid);
        map.put("origin", origin);
        map.put("version", version);
        map.put("charset", charset);
        map.put("interface_id", interface_id);
        map.put("timestamp", System.currentTimeMillis() + "");
        return map;
    }

    public static Map<String, String> initMap(String interface_id, String sign) {
        Map<String, String> stringStringMap = initMap(interface_id);
        if (sign != null && !"".equals(sign)) {
            stringStringMap.put("sign", sign);
        }
        return stringStringMap;
    }

    public  static String initBizContent(String servicename, Map<String, String> params) {
        Map<String, String> paramMap =new HashMap();
        paramMap.put("app_id", appid);
        paramMap.put("servicename", servicename);
        if (params != null) {
            paramMap.put("params", JSON.toJSONString(params));
        }
        return JSON.toJSONString(paramMap);
    }

    /**
     * 获取票据签名sign
     */
    public static String getSign(String interface_id, String bizContent) throws Exception {
        String sign = "";
        Map<String, String> map = initMap(interface_id);
        map.put("biz_content", bizContent);
        if ("1".equals(signType)) {
            sign = SignUtil.rsaSign(map, privateKey, charset, "RSA");
        } else {
            String url = "https://wfw.isdapp.shandong.gov.cn/jmasapi/jmas-api-gateway-server/createsign.do";
            JSONObject signObj = (JSONObject) HttpClientUtils.sendPost(url, map);
            JSONObject dataObj = signObj.getJSONObject("data");
            sign = dataObj.get("sign").toString();
        }
        System.out.println(sign);
        return sign;
    }

    /**
     * 通过票据获取令牌
     */
    public static Object getTokenByTicket(String sign, String ticket) throws Exception {
        String url = "https://wfw.isdapp.shandong.gov.cn/jmasapi/jmas-api-gateway-server/gateway.do";
        Map<String, String> map = initMap("ticketvalidate");
        map.put("sign", sign);
        Map<String, String> params =new HashMap();
        params.put("ticket", ticket);
        String bizContent = initBizContent("ticketValidate", params);
        map.put("biz_content", bizContent);
        return HttpClientUtils.sendPost(url, map);
    }

    /**
     * 根据token获取个人信息
     */
    public static Object getInfoByToken(String sign, String token) throws Exception {
        String url = "https://wfw.isdapp.shandong.gov.cn/jmasapi/jmas-api-gateway-server/gateway.do";
        Map<String, String> map = initMap("findoutsideuserbytoken");
        map.put("sign", sign);
        Map<String, String> params =new HashMap();
        params.put("token", token);
        String bizContent = initBizContent("findOutsideUserByToken", params);
        map.put("biz_content", bizContent);
        return HttpClientUtils.sendPost(url, map);
    }
    /**
     * 根据token获取法人信息
     */
    public static Object getEntepriseInfoByToken(String sign, String token) throws Exception {
        String url = "https://wfw.isdapp.shandong.gov.cn/jmasapi/jmas-api-gateway-server/gateway.do";
        Map<String, String> map = initMap("findcoruserytoken");
        map.put("sign", sign);
        Map<String, String> params =new HashMap();
        params.put("token", token);
        String bizContent = initBizContent("findCorUserByToken", params);
        map.put("biz_content", bizContent);
        return HttpClientUtils.sendPost(url, map);
    }

    /**
     * @Description:解密网关返回的密文
     */
    public static String getContent(String secret) throws Exception {
        // rsa私钥（在平台应用详情处复制）
        String decrypt = RasUtil.decrypt(secret, RasUtil.getPrivateKey(privateKey));
        return decrypt;
    }

    public static void main(String[] args) {
        String username = "A2222";	//I开头表示个人 A开头表示企业
        String usertype = "1";//省平台返回的用户类型 1表示个人 2表示法人
        if((username.startsWith("I") && usertype.equals("2")) || (username.startsWith("A") && usertype.equals("1"))){//表示CA与省平台登录的用户类型不匹配
            System.out.println("不匹配");
        }

//        Map<String, String> params =new HashMap();
//        try {
//            //根据票据信息获取Token
//            String ticket = "9a7348e583318356946d153e206ad9ee";
//            //获取签名信息
//            String sign = StyrzService.getSign("ticketvalidate", "");
//            System.out.println("sign:"+ sign);
//
//            JSONObject tokenByTicket = (JSONObject) StyrzService.getTokenByTicket(sign, ticket);
//            System.out.println(tokenByTicket.toJSONString());
//            String tokenSecret = tokenByTicket.get("data").toString();
//            System.out.println("tokenSecret:"+ tokenByTicket.get("data").toString());
//
//            // 网关返回的密文对秘密解密获取token
//            String tokenStr = getContent(tokenSecret);
//            System.out.println(tokenStr);
//            tokenStr = tokenStr.replaceAll("\\\\", "");
//            tokenStr = tokenStr.replaceAll("\"\\{", "{").replaceAll("}\"", "}");
//            System.out.println(tokenStr);
//            JSONObject parse = JSON.parseObject(tokenStr);
//            JSONObject dataObj = parse.getJSONObject("data");
//            System.out.println("tokne:"+ dataObj.getString("token"));
//            String token = dataObj.getString("token");
//
//            //根据token获取个人信息
//            JSONObject infoByToken = (JSONObject) StyrzService.getInfoByToken(sign, token);
//            System.out.println(infoByToken.toJSONString());
//            System.out.println(infoByToken.get("data").toString());
//            String tokenInfo = infoByToken.get("data").toString();
//            String info = getContent(tokenInfo);
//            System.out.println(info);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }
}
